<template>
  <el-select
    v-model="selectedUserIds"
    multiple
    filterable
    placeholder="请选择"
    @change="handleMultipleNodeChange"
  >
    <el-option
      v-for="item in userList"
      :key="item.id"
      :label="item.nickname"
      :value="item.id"
    >
      <span>{{ item.nickname }}</span>
    </el-option>
  </el-select>
</template>

<script lang="ts" setup>
import * as UserApi from '@/api/system/user'

defineOptions({ name: 'SystemUserSelect' })

const props = defineProps({
  modelValue: {
    type: [String, Array],
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'node-change'])

const { t } = useI18n() // 国际化

const userList = ref<UserApi.UserVO[]>([])

const selectedUserIds = computed({
  get: () => {
    if (typeof props.modelValue === 'string') {
      return props.modelValue ? props.modelValue.split(',').map(Number) : []
    }
    return props.modelValue || []
  },
  set: (val) => {
    emit('update:modelValue', val.join(','))
  }
})

const getList = async () => {
  const list = await UserApi.getSimpleUserList()
  userList.value = list
}

/** 处理员工选择 */
const handleMultipleNodeChange = async (userIds: number[]) => {
  const arr = userList.value.filter((item) => {
    return userIds.includes(item.id)
  })
  emit('node-change', arr)
}

/** 初始化 */
onMounted(async () => {
  await getList()
})
</script>
